package services.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.common.bean.AnXinSignBean;
import models.common.bean.CreditLimitCompanyInfo;
import models.common.bean.CreditorRightDebt;
import models.common.entity.t_company_info;
import models.common.entity.t_credit_limit;
import models.common.entity.t_creditor_right_debt;
import models.common.entity.t_event_user;
import models.common.entity.t_information_assurance;
import models.common.entity.t_pact;
import models.common.entity.t_receivables_push;
import models.common.entity.t_setting_platform;
import models.common.entity.t_shareholder_sign;
import models.common.entity.t_supervisor_audit.AuditResult;
import models.common.entity.t_user;
import models.common.entity.t_user_credit;
import models.common.entity.t_user_credit_detail;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;

import com.sun.org.apache.bcel.internal.generic.ATHROW;

import play.mvc.Http.Request;
import services.base.BaseService;

import common.constants.SettingKey;
import common.enums.NoticeScene;
import common.enums.ServiceType;
import common.utils.DateUtil;
import common.utils.Factory;
import common.utils.FeeCalculateUtil;
import common.utils.LoggerUtil;
import common.utils.OrderNoUtil;
import common.utils.PageBean;
import common.utils.ResultInfo;
import common.utils.file.FileUtil;
import common.utils.number.Arith;

import daos.common.CompanyInfoDao;
import daos.common.CreditLimitDao;

/**
 * 信用额度申请service
 * 
 * @author fanghanyong
 * @version 2018-01-11 上午11:00:00
 */
public class CreditLimitService extends BaseService<t_credit_limit> {

	protected static DigitalCommercialPaperService digitalCommercialPaperService = Factory
			.getService(DigitalCommercialPaperService.class);

	protected static UserFundService userFundService = Factory
			.getService(UserFundService.class);

	protected static CreditorRightDebtService creditorRightDebtService = Factory
			.getService(CreditorRightDebtService.class);

	protected static InformationAssuranceService informationAssuranceService = Factory
			.getService(InformationAssuranceService.class);

	protected static ShareholderSignService shareholderSignService = Factory
			.getService(ShareholderSignService.class);

	protected CompanyInfoDao companyInfoDao = Factory
			.getDao(CompanyInfoDao.class);

	protected static UserCreditDetailService userCreditDetailService = Factory
			.getService(UserCreditDetailService.class);

	protected static CreditLimitDao creditLimitDao = Factory
			.getDao(CreditLimitDao.class);

	public CreditLimitService() {
		creditLimitDao = Factory.getDao(CreditLimitDao.class);
		super.basedao = this.creditLimitDao;
	};

	protected static CreditLimitService creditLimitService = Factory
			.getService(CreditLimitService.class);

	protected static CompanyInfoService companyInfoService = Factory
			.getService(CompanyInfoService.class);

	protected static ReceivablesPushService receivablesPushService = Factory
			.getService(ReceivablesPushService.class);

	protected static NoticeService noticeService = Factory
			.getService(NoticeService.class);

	protected static UserCreditService userCreditService = Factory
			.getService(UserCreditService.class);
	
	protected static UserService userService = Factory
			.getService(UserService.class);
	
	protected static SettingService settingService = Factory
			.getService(SettingService.class);

	/**
	 * 新增管理员审核操作结果
	 * 
	 * @param type
	 * @param supervisor_id
	 * @param auditResult
	 * @param describe
	 * @return
	 * @author xiaojun
	 * @version 2017-4-18 上午11:56:22
	 */
	public boolean addCreditLimit(String remark, long user_id,
			t_credit_limit t, String file_url, double request_limit) {
		if (t == null) {
			t = new t_credit_limit();
		}
		t.request_limit = request_limit;
		t.remark = remark;
		t.time = new Date();
		t.setAudit_status(AuditResult.HAVE_NO_AUDIT);
		t.user_id = user_id;
		t.file_url = file_url;
		return creditLimitDao.save(t);
	}

	/**
	 * 分页查询 回款计划
	 * 
	 * @param currPage
	 * @param pageSize
	 * @param userId
	 * @return
	 * 
	 * @author Chenzhipeng
	 * @createDate 2016年1月18日
	 * 
	 */
	public PageBean<t_credit_limit> pageOfCreditLimit(int currPage,
			int pageSize, long userId) {

		return creditLimitDao.pageOfCreditLimit(currPage, pageSize, userId);
	}

	/**
	 * 查询未审核的申请记录
	 * 
	 * @param user_id
	 * @param status
	 * @return
	 * @author xiaojun
	 * @version 2017-10-30
	 */
	public t_credit_limit findCredit_limit(long user_id, int status) {
		return creditLimitDao.findByColumn(" user_id = ? AND audit_status = ?",
				user_id, status);
	}

	/**
	 * 
	 * 更新数据
	 * 
	 * @param t
	 * @return
	 * @author xiaojun
	 * @version 2017-10-30
	 */
	public boolean save(t_credit_limit t) {
		return creditLimitDao.save(t);
	}

	/**
	 * 更新申请额度记录的审核状态
	 * 
	 * @param id
	 * @param audit_status
	 * @return
	 * 
	 * @author fanghanyong
	 * @createDate 2018年01月11日
	 * 
	 */
	public int updateById(long id, int audit_status) {

		return creditLimitDao.updateById(id, audit_status);
	}

	/**
	 * 分页查询 查询放款人对应的申请列表
	 * 
	 * @param currPage
	 * @param pageSize
	 * @param supervisorId
	 * @return
	 * 
	 * @author fanghanyong
	 * @createDate 2018年01月11日
	 * 
	 */
	public PageBean<CreditLimitCompanyInfo> pageOfCreditLimitBysupervisorId(
			int currPage, int pageSize, long supervisorId) {

		return creditLimitDao.pageOfCreditLimitBysupervisorId(currPage,
				pageSize, supervisorId);
	}

	/**
	 * 通过放款人的ID和用户的登录ID查询 还没有增加到推送表的授信申请信息表
	 * 
	 * @param id
	 *            放款人ID
	 * @param userId
	 *            登录的用户ID
	 * @return
	 * @author fanghanyong
	 * @version 2018-1-15
	 */
	public List<t_credit_limit> findByUserIdLenderId(long supervisorId,
			long userId) {
		return creditLimitDao.findByUserIdLenderId(supervisorId, userId);
	}

	/**
	 * 添加授信申请记录
	 * 
	 * @param debtIdLong
	 *            授信申请的账款信息
	 * @param lenderId
	 *            授信申请的放款人信息
	 * @param credit_amount
	 *            授信申请的金额
	 * @param credit_remark
	 *            授信申请的说明
	 * @param userId
	 *            当前登录的用户
	 * @return
	 * @author fanghanyong
	 * @version 2018-1-15
	 * @param endMonth 
	 */
	public static ResultInfo addUserCreditDetail(long creditId,
			long lenderId, double credit_amount, String credit_remark,
			long userId, String financial_data, String income_tax,
			String bank_statement, String utility_bill, String pay_sheet,
			String purchase_sale_contracts,
			String financing_credit_information, String other_information, int endMonth) {

		// 定义错误信息结果集
		ResultInfo result = new ResultInfo();

		// 获取当前的时间
		Date date = new Date();
		
		//查账款信息
		t_creditor_right_debt creditor_right_debt = creditorRightDebtService.findByID(creditId);
		
		if(creditor_right_debt == null){
			result.code = -1;
			result.msg = "获取账款信息失败，请重新选择";
			return result;
		}
		
		t_user user = userService.findByID(userId);
		
		if(user == null){
			result.code = -1;
			result.msg = "获取用户信息失败，请重新登录";
			return result;
		}
		
		// 获取放款人的全称
		t_company_info companyInfo = companyInfoService
				.findCompanyInfoByUserId(lenderId);
		if (companyInfo == null) {
			result.code = -1;
			result.msg = "获取放款人的全称失败";
			LoggerUtil.error(true, "获取放款人的全称失败");
			return result;
		}

		String lenderFullName = companyInfo.full_name;
		// 给放款人的授信申请表赋值
		t_credit_limit creditLimit = new t_credit_limit(financial_data,
				income_tax, bank_statement, utility_bill, pay_sheet,
				purchase_sale_contracts, financing_credit_information,
				other_information);
		creditLimit.time = date;
		creditLimit.request_limit = credit_amount;
		creditLimit.remark = credit_remark;
		creditLimit.supervisor_id = lenderId;
		creditLimit.supervisor_name = lenderFullName;
		// 授信申请状态默认为0
		creditLimit.audit_status = 0;
		creditLimit.user_id = userId;
		creditLimit.duration = endMonth;

		// 添加授信申请表的记录
		boolean saveCreditLimitFlag = creditLimitDao.save(creditLimit);

		if (!saveCreditLimitFlag) {
			result.code = -1;
			result.msg = "添加额度申请表失败";
			LoggerUtil.error(true, "添加额度申请表失败");
			return result;
		}
		// 查询授信申请表的记录是否添加成功
		List<t_credit_limit> CreditLimitIdList = creditLimitDao
				.findByUserIdLenderId(lenderId, userId);
		if (CreditLimitIdList == null || CreditLimitIdList.size() <= 0 ) {
			result.code = -1;
			result.msg = "添加额度申请表失败";
			return result;
		}
		
		//增加推送关系
		t_receivables_push receivablesPush = new t_receivables_push();
		
		receivablesPush.credit_limit_id = CreditLimitIdList.get(0).id;
		receivablesPush.time = date;
		receivablesPush.lender_id = lenderId;
		receivablesPush.user_id = userId;
		receivablesPush.status = 1;
		receivablesPush.creditor_right_id = creditor_right_debt.id;
		boolean saveCreditPushFlag = receivablesPushService
				.save(receivablesPush);
		if (!saveCreditPushFlag) {
			result.code = -1;
			result.msg = "添加账款推送关系表失败";
			LoggerUtil.error(true, "添加账款推送关系表失败");
			return result;
		}
		
		/** 给应付账款的债权人发送通知 */
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("user_name", creditor_right_debt.creditor_name);
		condition.put("debt_name", creditor_right_debt.debt_person_name);
		noticeService.sendSysNotice(creditor_right_debt.company_id,
				NoticeScene.PUSH_CREDIT, condition);

		// 获取当前登录用户的全称
		t_company_info companyInfoUser = companyInfoService
				.findCompanyInfoByUserId(userId);

		String companyInfoserId = companyInfoUser.full_name;

		/** 发送通知 */
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("user_name", lenderFullName);
		param.put("credit_name", companyInfoserId);
		noticeService.sendSysNotice(lenderId,
				NoticeScene.PACKAGING_CREDIT_LIMIT_DEBT, param);
		
		t_user_credit user_credit = userCreditService.findByUserId(userId, lenderId);
		//票信额度管理费 率
		double fee = 0.0;
		//票信额度管理费
		double custodian_fee = 0.0;
		if(user_credit == null ){
			t_setting_platform setting = settingService.findSettingByKey(SettingKey.CUSTODIAN_FEE_MAX);
			fee = Double.parseDouble(setting._value);
			//TODO
			if(endMonth > 0 && endMonth < 13){
				//票信额度管理费
				custodian_fee = Arith.div(Arith.mul(
						Arith.mul(credit_amount, fee),
						endMonth), 100, 2);
				
				Map<String,Object> condistion = new HashMap<String,Object>();
				condistion.put("user_name", user.company_full_name);
				condistion.put("custodian_fee", custodian_fee);
				noticeService.sendSysNotice(user.id,
						NoticeScene.CREDIT_LIMIT_DEBT, condistion);
			}else if(endMonth == 0){
				//票信额度管理费
				custodian_fee = Arith.div(Arith.mul(
						Arith.mul(credit_amount, fee),
						12), 100, 2);
				
				Map<String,Object> condistion = new HashMap<String,Object>();
				condistion.put("user_name", user.company_full_name);
				condistion.put("custodian_fee", custodian_fee);
				noticeService.sendSysNotice(user.id,
						NoticeScene.CREDIT_LIMIT_DEBT, condistion);
			}
		}else{
			fee = user_credit.custodian_fee;
			//TODO
			endMonth = DateUtil.creditLenderMonth(new Date(), user_credit.end_time);
			//票信额度管理费
			custodian_fee = Arith.div(Arith.mul(
					Arith.mul(credit_amount, fee),
					endMonth), 100, 2);
			
			Map<String,Object> condistion = new HashMap<String,Object>();
			condistion.put("user_name", user.company_full_name);
			condistion.put("custodian_fee", custodian_fee);
			noticeService.sendSysNotice(user.id,
					NoticeScene.CREDIT_LIMIT_DEBT, condistion);
			
		}
		
		

		result.code = 1;
		result.msg = "预授信额度申请成功";
		result.obj = custodian_fee;
		Request request = Request.current();
		
		Map<String, String> userEventParam = new HashMap<String, String>();
		userEventParam.put("userName", companyInfoserId);
		userEventParam.put("ip",request.remoteAddress.toString());
		
		userService.addUserEvent(userId, t_event_user.Event.ADD_CREDITLIMIT, userEventParam);
		
		return result;
	}

	/**
	 * 查询授信申请表的信息
	 * 
	 * @param creditID
	 *            授信申请id
	 * @return
	 * @author fanghanyong
	 * @version 2018-1-18
	 */
	public t_credit_limit findByCreditID(long creditID) {
		return findByColumn(" id = ?", creditID);
	}

	/**
	 * 添加审核结果信息
	 * 
	 * @param credit_amount_submit
	 *            预授信额度
	 * @param financing_confine_submit
	 *            融通比例不超过
	 * @param credebt_amount_submit
	 *            单笔融通面额不超过
	 * @param bond_amount_submit
	 *            保证金比例
	 * @param custodian_fee_submit
	 *            额度管理费率
	 * @param shareholder_sign_id
	 *            保证人信息
	 * @param applyUserId
	 *            融通人ID
	 * 
	 * @param operationType
	 *            操作类型 1-通过审核 2-不通过审核
	 * @param request_limit_submit
	 *            预授信申请额度
	 * @param creditId
	 *            授信申请
	 * @param userId
	 *            放款人的id
	 * @param is_pledge_management
	 *            融通人授信申请审核时的签署方式
	 * @author fanghanyong
	 * @version 2018-1-18
	 * @param endMonth 
	 * @return
	 */
	public static ResultInfo addCreditAuditInfo(double credit_amount_submit,
			double financing_confine_submit, double credebt_amount_submit,
			double bond_amount_submit, double custodian_fee_submit,
			String shareholder_sign_id, long applyUserId, int operationType,
			double request_limit_submit, long creditId, long userId,
			int is_pledge_management, String ipAddr,String endDate, int endMonth) {

		ResultInfo result = new ResultInfo();
		
		// 获取放款人的全称
		t_company_info companyInfo = companyInfoService
				.findCompanyInfoByUserId(userId);
		if (companyInfo == null) {
			result.code = -1;
			result.msg = "获取放款人的全称失败";
			return result;
		}
		String lenderFullName = companyInfo.full_name;

		// 获取融通人的全称
		t_company_info companyInfoUser = companyInfoService
				.findCompanyInfoByUserId(applyUserId);
		if (companyInfoUser == null) {
			result.code = -1;
			result.msg = "获取融通人的全称失败";
			return result;
		}

		String companyInfoserId = companyInfoUser.full_name;

		// 获取当前的时间
		Date date = new Date();

		// 获取到期时间
		
		Date end_time = null;
		// 获取授信编号
		String credit_granting_code = OrderNoUtil.getCreditCode();

		// 业务流水号
		String service_order_no = OrderNoUtil.getNormalOrderNo(
				ServiceType.DONEORDER_QUERY, "");

		// 获取合同编号
		String contract_id = OrderNoUtil.getAssurance();
		
		//获取该授信申请绑定的应付账款信息
		t_receivables_push receivables_push = receivablesPushService.findTRPBySql(creditId,userId,applyUserId);
		
		t_creditor_right_debt creditorRightDebt = creditorRightDebtService.findByID(receivables_push.creditor_right_id);
		
		//TODO
		// 审核通过操作
		if (operationType == 1) {
			if(endMonth == 0 && (endDate == null || "".equals(endDate))){
				result.code = -1;
				result.msg = "请填写到期日期";
				return result;
			}
			if(endMonth == 0 && endDate != null){
				end_time = DateUtil.strToDate(endDate, "yyyy/MM/dd");
			}else{
				end_time = DateUtil.addMonth(new Date(),endMonth);
				
			}
			// 授信天数
			int dateCount = 0;
			try{
				dateCount = DateUtil.getDaysDiffCeil(date, end_time);
			}catch(Exception e){
				result.code = -1;
				result.msg = "截止日期不能小于起始日期，或者是同一天";
				return result;
			}
			//流水号
			String serrino = service_order_no;
			// 查询当前授信用户的额度信息
			t_user_credit userCredit = userCreditService.findByUserId(
					applyUserId, userId);
			if (userCredit != null) {
				dateCount = DateUtil.getDaysDiffCeil(date, userCredit.end_time);
				endMonth = DateUtil.creditLenderMonth(date, userCredit.end_time);
				if(endMonth== 0){
					endMonth = 1;
				}
			}else{
				if(endMonth > 12){
					
					result.code = -1;
					result.msg = "到期日期不能大于授信起始日期一年";
					return result;
				}
			}
			// 判断放款人的可用余额是否大于票信流转服务费
			double fee = Double.valueOf(settingService
					.findSettingValueByKey(SettingKey.CUSTODIAN_FEE));
			
			//额度管理费
			double custodian_fee = Arith.div(Arith.mul(
					Arith.mul(credit_amount_submit, custodian_fee_submit),
					endMonth), 100, 2);

			//票信流转服务费
			double leader_custodian_fee = Arith.div(
					Arith.mul(Arith.mul(credit_amount_submit, fee), endMonth),
					100, 2);

			if(Arith.sub(custodian_fee, leader_custodian_fee)<0){
				result.code = -1;
				result.msg = "授信申请人缴纳的票信额度管理费("+custodian_fee+"元)低于放款人缴纳的票信流转服务费("+leader_custodian_fee+"元)，票信额度管理费率应该大于或者等于百分之"+fee+"";
				return result;
			}
			
			// 判断预授信额度是否为0
			if (credit_amount_submit == 0 || credit_amount_submit == 0.0
					|| credit_amount_submit == 0.00) {
				result.code = -1;
				result.msg = "预授信额度不能为空";
				return result;
			}

			// 判断单笔融通面额是否为0
			if (credebt_amount_submit == 0 || credebt_amount_submit == 0.0
					|| credebt_amount_submit == 0.00) {
				result.code = -1;
				result.msg = "单笔融通面额不能为空";
				return result;
			}

			// 判断保证金比例是否为0
			if (bond_amount_submit > 100 || bond_amount_submit > 100.0
					|| bond_amount_submit > 100.00) {
				result.code = -1;
				result.msg = "保证金比例不能超过100";
				return result;
			}
			if(bond_amount_submit == 0){
				// 流转费用的结算
				ResultInfo resultfee = digitalCommercialPaperService
						.userTransaction(applyUserId, userId,
								credit_amount_submit, endMonth,
								custodian_fee_submit,serrino);
				if(resultfee.code==0){
					
					Map<String, Object> sparam = new HashMap<String, Object>();
					sparam.put("lenderFullName", lenderFullName);
					sparam.put("applyUserName", companyInfoserId);
					sparam.put("request_limit_submit", request_limit_submit);
					sparam.put("credit_amount_submit", credit_amount_submit);
					sparam.put("custodian_fee_submit", custodian_fee);
					 noticeService.sendSysNotice(applyUserId,
							NoticeScene.PACKAGING_USER_LIMIT_SUCC, sparam);
				
					result.code = -1;
					result.msg = resultfee.msg;
					return result;
				}else if (resultfee.code == -1) {
					LoggerUtil.error(true,resultfee.msg );
					result.code = -1;
					result.msg = resultfee.msg;
					return result;
				}
			}
			
			// 修改或者增加额度申请表t_user_credit和添加额度申请明细表t_user_credit_detail
			ResultInfo resultCreditInfo = saveCreditInfo(credit_amount_submit,
					financing_confine_submit, credebt_amount_submit,
					bond_amount_submit, custodian_fee_submit, applyUserId,
					userId, lenderFullName, companyInfoserId, date, end_time,
					credit_granting_code, service_order_no,custodian_fee);
			if (resultCreditInfo.code < 1) {
				LoggerUtil.error(true,resultCreditInfo.msg );
				result.code = -1;
				result.msg = resultCreditInfo.msg;
				return result;
			}
			
			// 查询当前授信用户的额度信息
			t_user_credit newUserCredit = userCreditService.findByUserId(
					applyUserId, userId);
			if(newUserCredit == null){
				result.code = -1;
				result.msg = "获取不到授信信息";
				return result;
			}
			//使用同一授信的授信编号
			credit_granting_code = newUserCredit.credit_granting_code;
			
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("lenderFullName", lenderFullName);
			param.put("applyUserName", companyInfoserId);
			param.put("request_limit", request_limit_submit);
			param.put("credit_amount_submit", credit_amount_submit);
			param.put("custodian_fee_submit", custodian_fee);
			if(newUserCredit.start_time == null){
				
				param.put("start_time", new Date());
			}else{
				param.put("start_time",newUserCredit.start_time );
				
			}
			 double bond_money = Arith.mul(Arith.div(bond_amount_submit, 100, 2), credit_amount_submit);
			param.put("end_time",  newUserCredit.end_time);
			param.put("ratio", financing_confine_submit);
			param.put("bond_money",bond_money);
			param.put("margin", bond_amount_submit);
			
			
			// 更新授信申请表的信息
			ResultInfo resultCreditLimit = CreditLimit(credit_amount_submit,
					creditId, date, end_time, credit_granting_code,
					operationType, applyUserId, lenderFullName,
					companyInfoserId, request_limit_submit);

			if (resultCreditLimit.code < 1) {
				result.code = -1;
				result.msg = resultCreditLimit.msg;
				return result;
			}
			
			if(bond_amount_submit == 0){
				
				
				// 添加额度申请明细表t_user_credit_detail
				ResultInfo resultCreditDetailInfo = CreditDetail(
						credit_amount_submit, applyUserId, userId, lenderFullName,
						companyInfoserId, date, end_time, credit_granting_code,
						service_order_no);

				if (resultCreditDetailInfo.code < 1) {
					result.code = -1;
					result.msg = resultCreditDetailInfo.msg;
					return result;
				}
				
				//根据绑定的应付账款信息，将一部分授信额度直接转给应付账款债权人
				result = userCreditService.toApply(creditorRightDebt,newUserCredit.user_id,newUserCredit.lender_id);
				if (result.code < 1) {
					result.code = -1;
					return result;
				}
				//审核成功，通知授信申请用户
				if (shareholder_sign_id == null || "".equals(shareholder_sign_id)) {
					noticeService.sendSysNotice(applyUserId,
							NoticeScene.PACKAGING_CREDIT_LIMIT_SUCC, param);
					result.code = 1;
					result.msg = "审核操作成功";
					return result;
				}
				noticeService.sendSysNotice(applyUserId,
						NoticeScene.PACKAGING_CREDIT_LIMIT_SUCC_DUTY, param);

				// 添加保证信息表t_information_assurance
				ResultInfo resultAssuranceInfo = AssuranceMsg(applyUserId, userId,
						lenderFullName, date, contract_id, is_pledge_management,
						creditId);

				if (resultAssuranceInfo.code < 1) {
					result.code = -1;
					result.msg = resultAssuranceInfo.msg;
					return result;
				}
				// 添加保证签字表t_information_assurance
				ResultInfo resultShareHoldSign = ShareHoldSign(shareholder_sign_id,
						applyUserId, userId, date, contract_id, lenderFullName,
						companyInfoserId, is_pledge_management, creditId, ipAddr);

				if (resultShareHoldSign.code < 1) {
					result.code = -1;
					result.msg = resultShareHoldSign.msg;
					return result;
				}
			}else{
				
				if (shareholder_sign_id == null || "".equals(shareholder_sign_id)) {
					
					noticeService.sendSysNotice(applyUserId,
							NoticeScene.CREDIT_LIMIT_SUCC_BOND, param);
					
					result.code = 1;
					result.msg = "审核操作成功";
					return result;
				}
				noticeService.sendSysNotice(applyUserId,
						NoticeScene.CREDIT_LIMIT_SUCC_DUTY_BOND, param);
				// 添加保证信息表t_information_assurance
				ResultInfo resultAssuranceInfo = AssuranceMsg(applyUserId, userId,
						lenderFullName, date, contract_id, is_pledge_management,
						creditId);

				if (resultAssuranceInfo.code < 1) {
					result.code = -1;
					result.msg = resultAssuranceInfo.msg;
					return result;
				}
				// 添加保证签字表t_information_assurance
				ResultInfo resultShareHoldSign = ShareHoldSign(shareholder_sign_id,
						applyUserId, userId, date, contract_id, lenderFullName,
						companyInfoserId, is_pledge_management, creditId, ipAddr);

				if (resultShareHoldSign.code < 1) {
					result.code = -1;
					result.msg = resultShareHoldSign.msg;
					return result;
				}
			}
			
			

		} else {
			// 更新授信申请表的信息
			ResultInfo resultRightPush = CreditorRightPush(applyUserId,
					creditId, userId);

			if (resultRightPush.code < 1) {
				result.code = -1;
				result.msg = resultRightPush.msg;
				return result;
			}

			// 更新授信申请表的信息
			ResultInfo resultCreditLimit = CreditLimit(credit_amount_submit,
					creditId, date, end_time, credit_granting_code,
					operationType, applyUserId, lenderFullName,
					companyInfoserId, request_limit_submit);

			if (resultCreditLimit.code < 1) {
				result.code = -1;
				result.msg = resultCreditLimit.msg;
				return result;
			}
			//审核失败，通知用户
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("lenderFullName", lenderFullName);
			param.put("applyUserName", companyInfoserId);
			param.put("request_limit", request_limit_submit);
			noticeService.sendSysNotice(applyUserId,
					NoticeScene.PACKAGING_CREDIT_LIMIT_FAILED, param);

		}

		result.code = 1;
		result.msg = "审核操作成功";
		return result;
	}

	/**
	 * 更新账款推送表和账款表信息
	 * 
	 * @param applyUserId
	 *            申请人id
	 * @param creditId
	 *            授信id
	 * @param userId
	 *            放款人id
	 * @author fanghanyong
	 * @version 2018-1-19
	 * @return
	 */
	public static ResultInfo CreditorRightPush(long applyUserId, long creditId,
			long userId) {

		ResultInfo result = new ResultInfo();

		// 查询当前的账款信息
		List<CreditorRightDebt> creditorRightDebt = creditorRightDebtService
				.findByCreditUserIdLenderId(userId, applyUserId, creditId);
		if (creditorRightDebt == null) {
			result.code = -1;
			result.msg = "用户没有提交对应的账款信息";
			return result;
		}
		for (int i = 0; i < creditorRightDebt.size(); i++) {
			// 更新推送表的状态信息
			if (creditorRightDebt.get(i).getCredit_status().code != 3) {
				int updatePushCount = receivablesPushService
						.updateReceivablesPushStatus(
								applyUserId,
								creditorRightDebt.get(i).creditor_right_id,
								3,
								creditorRightDebt.get(i).getCredit_status().code,
								userId);
				if (updatePushCount <= 0) {
					LoggerUtil.error(true, "更改表状态失败");
					result.code = -1;
					result.msg = "更新表状态失败";
					return result;
				}
			}
			// 更新账款表的状态信息
			boolean updateDebtFlag = creditorRightDebtService
					.updateStatusLeaderId(3, creditorRightDebt.get(i).getStatus().code,
							creditorRightDebt.get(i).creditor_right_id, 0);
			if (!updateDebtFlag) {
				LoggerUtil.error(true, "更改表状态失败");
				result.code = -1;
				result.msg = "更新表状态失败";
				return result;
			}
		}
		result.code = 1;
		result.msg = "更新账款推送表和账款表信息成功";
		return result;
	}

	/**
	 * 更新授信申请表的信息
	 * 
	 * @param credit_amount_submit
	 *            授信额度
	 * @param creditId
	 *            授信申请
	 * @param date
	 *            当前时间
	 * @param end_time
	 *            授信截止时间
	 * @param credit_granting_code
	 *            授信编号
	 * @param type
	 *            审核类型 1-通过 2-不通过
	 * @param applyUserId
	 *            申请人
	 * @param lenderFullName
	 *            放款人姓名
	 * @param companyInfoserId
	 *            申请人姓名
	 * @param request_limit
	 *            预授信申请额度
	 * @author fanghanyong
	 * @version 2018-1-19
	 * @return
	 */
	public static ResultInfo CreditLimit(double credit_amount_submit,
			long creditId, Date date, Date end_time,
			String credit_granting_code, int type, long applyUserId,
			String lenderFullName, String companyInfoserId, double request_limit) {

		ResultInfo result = new ResultInfo();

		// 更新授信申请表的信息
		t_credit_limit creditLimit = creditLimitService
				.findByCreditID(creditId);
		if (creditLimit == null) {
			result.code = -1;
			result.msg = "更改授信申请表失败";
			LoggerUtil.error(true, "更改授信申请表失败");
			return result;
		}
		if (type == 1) {
			creditLimit.audit_amount = credit_amount_submit;
			creditLimit.audit_status = 2;
			creditLimit.credit_granting_code = credit_granting_code;
			creditLimit.start_time = date;
			creditLimit.end_time = end_time;
			creditLimit.audit_time = date;
			
		} else {
			creditLimit.audit_amount = credit_amount_submit;
			creditLimit.audit_status = 1;
			creditLimit.credit_granting_code = credit_granting_code;
			creditLimit.start_time = date;
			creditLimit.end_time = end_time;
			creditLimit.audit_time = date;
			
		}
		boolean creditLimitFlag = creditLimitDao.save(creditLimit);
		if (!creditLimitFlag) {
			result.code = -1;
			result.msg = "更改授信申请表失败";
			LoggerUtil.error(true, "更改授信申请表失败");
			return result;
		}

		result.code = 1;
		result.msg = "更改授信申请表成功";
		return result;
	}

	/**
	 * 添加保证信息表t_information_assurance
	 * 
	 * @param shareholder_sign_id
	 *            保证人信息（shaUserId@#@shareholderMobile@#@shareholderName#_#
	 *            shaUserId@#@shareholderMobile@#@shareholderName）
	 * @param applyUserId
	 *            放款人id
	 * @param userId
	 *            申请用户id
	 * @param date
	 *            当前时间
	 * @param contract_id
	 *            签字协议（合同编号/同步合同表pact_no）
	 * @param lenderFullName
	 *            放款人姓名
	 * @param companyInfoUser
	 *            申请人姓名
	 * @param is_pledge_management
	 *            签署方式
	 * @param creditId
	 *            授信申请表id
	 * @author fanghanyong
	 * @version 2018-1-19
	 * @return
	 */
	public static ResultInfo ShareHoldSign(String shareholder_sign_id,
			long applyUserId, long userId, Date date, String pact_no,
			String lenderFullName, String companyInfoUser,
			int is_pledge_management, long creditId, String ip) {

		ResultInfo result = new ResultInfo();

		// 查询当前授信用户的额度信息
		t_user_credit userCreditCheck = userCreditService.findByUserId(
				applyUserId, userId);

		if (userCreditCheck == null) {
			result.code = -1;
			result.msg = "添加或者修改额度申请表失败";
			return result;
		}

		// 查询保证信息表信息
		t_information_assurance inforAssCheck = informationAssuranceService
				.findByUserId(applyUserId, userId, creditId, pact_no);
		if (inforAssCheck == null) {
			result.code = -1;
			result.msg = "添加保证信息表失败";
			LoggerUtil.error(true, "添加保证信息表失败");
			return result;
		}
		// 解析保证人信息
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		if (shareholder_sign_id != null && shareholder_sign_id != "") {
			String[] shareholderSignResult = shareholder_sign_id.split("#_#");
			for (int i = 0; i < shareholderSignResult.length; i++) {
				String[] shareholderSignSubResult = shareholderSignResult[i]
						.split("@#@");
				if (shareholderSignSubResult.length >= 3) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("shaUserId",
							Long.parseLong(shareholderSignSubResult[0]));
					map.put("shareholderMobile", shareholderSignSubResult[1]);
					map.put("shareholderName", shareholderSignSubResult[2]);
					list.add(map);
				}
			}
		}
		List<AnXinSignBean> anXinlist = new ArrayList<AnXinSignBean>();
		AnXinSignBean bean = null;
		t_user user = null;
		// 签章关键字
		StringBuffer key_name = new StringBuffer();
		// 增加保证人签字表信息
		for (int k = 0; k < list.size(); k++) {
			user = userService.findByID((Long) list.get(k).get("shaUserId"));
			if (user == null || user.vip_code == null) {
				result.code = -1;
				result.msg = "添加保证人"
						+ (String) list.get(k).get("shareholderName") + "失败!"
						+ "请检查保证人是否存在并绑定成功";
				LoggerUtil.error(true, result.msg);
				return result;
			}

			t_shareholder_sign shareholderSign = new t_shareholder_sign();
			shareholderSign.assurance_id = inforAssCheck.id;
			shareholderSign.user_id = user.id;
			shareholderSign.is_sign = 0;
			shareholderSign.sign_time = date;
			shareholderSign.contract_id = pact_no;
			shareholderSign.shareholder_mobile = (String) list.get(k).get(
					"shareholderMobile");
			shareholderSign.shareholder_name = (String) list.get(k).get(
					"shareholderName");
			boolean shareholderSignFlag = shareholderSignService
					.addShareholderSign(shareholderSign);
			if (!shareholderSignFlag) {
				result.code = -1;
				result.msg = "添加保证人签字表失败";
				LoggerUtil.error(true, "添加保证人签字表失败");
				return result;
			}
			int i = k + 1;
			key_name.append("（签名" + i + "）" + shareholderSign.shareholder_name
					+ "（签章）<br/>");
			bean = new AnXinSignBean(user.vip_code, 0, ip,
					shareholderSign.shareholder_name + "（签章）", pact_no);
			anXinlist.add(bean);

			/** 发送通知 */
			Map<String, Object> param = new HashMap<String, Object>();
			long shareID = (Long) list.get(k).get("shaUserId");
			param.put("shareName", (String) list.get(k).get("shareholderName"));
			param.put("lenderFullName", lenderFullName);
			param.put("applyUserName", companyInfoUser);
			param.put("contract_id", pact_no);
			noticeService.sendSysNotice(shareID,
					NoticeScene.SHARE_CREDIT_LIMIT_SUCC, param);

		}
		// 签署协议
		result = informationAssuranceService.savePact(inforAssCheck.id,
				userCreditCheck.lender_name, userCreditCheck.user_name,
				pact_no, anXinlist, key_name.toString());
		if (result.code < 1) {
			LoggerUtil.error(true, result.msg);
			return result;
		}
		t_pact pact = (t_pact) result.obj;

		inforAssCheck.contract_id = pact.contract_no;
		boolean save = informationAssuranceService.save(inforAssCheck);
		if (!save) {
			result.code = -1;
			result.msg = "更新保证信息表失败！";
			LoggerUtil.error(true, result.msg);
			return result;
		}

		result.code = 1;
		result.msg = "添加保证人签字表成功";
		return result;
	}

	/**
	 * 添加保证信息表t_information_assurance
	 * 
	 * @param applyUserId
	 *            放款人id
	 * @param userId
	 *            申请用户id
	 * @param lenderFullName
	 *            放款人名称
	 * @param date
	 *            当前时间
	 * @param contract_id
	 *            合同编号
	 * @param is_pledge_management
	 *            签署方式
	 * @param creditId
	 *            授信申请表id
	 * @author fanghanyong
	 * @version 2018-1-19
	 * @return
	 */
	public static ResultInfo AssuranceMsg(long applyUserId, long userId,
			String lenderFullName, Date date, String contract_id,
			int is_pledge_management, long creditId) {

		ResultInfo result = new ResultInfo();

		// 查询当前授信用户的额度信息
		t_user_credit userCreditCheck = userCreditService.findByUserId(
				applyUserId, userId);

		if (userCreditCheck == null) {
			result.code = -1;
			result.msg = "添加或者修改额度申请表失败";
			return result;
		}
		// 获取签署方式
		// 授信申请记录签署方式 0 自动签署 1 面签
		int isPledgeManagement = is_pledge_management;
		// 状态 0待签署 1已签署 2已失效 3已确认
		int status = 0;
		/*
		 * if (is_pledge_management == 1) { isPledgeManagement = 1; status = 0;
		 * }
		 */
		// 增加保证信息表信息
		t_information_assurance informationAssurance = new t_information_assurance();
		informationAssurance.time = date;
		informationAssurance.user_id = applyUserId;
		informationAssurance.status = status;
		informationAssurance.credit_limit_id = creditId;
		informationAssurance.contract_id = contract_id;
		informationAssurance.lender_id = userId;
		informationAssurance.lender_name = lenderFullName;
		informationAssurance.is_pledge_management = isPledgeManagement;
		boolean informationAssuranceFlag = informationAssuranceService
				.save(informationAssurance);
		if (!informationAssuranceFlag) {
			result.code = -1;
			result.msg = "添加保证信息表失败";
			LoggerUtil.error(true, "添加保证信息表失败");
			return result;
		}

		result.code = 1;
		result.msg = "添加保证信息表成功";
		return result;
	}

	/**
	 * 添加额度申请明细表t_user_credit_detail
	 * 
	 * @param credit_amount_submit
	 *            授信总额度
	 * @param applyUserId
	 *            持有人用户id
	 * @param userId
	 *            放款人id
	 * @param lenderFullName
	 *            放款人名称
	 * @param companyInfoserId
	 *            持有人名称
	 * @param date
	 *            当前时间
	 * @param end_time
	 *            授信截止时间
	 * @param credit_granting_code
	 *            授信编号
	 * @param service_order_no
	 *            业务流水号
	 * @return
	 * @author fanghanyong
	 * @version 2018-1-19
	 */
	public static ResultInfo CreditDetail(double credit_amount_submit,
			long applyUserId, long userId, String lenderFullName,
			String companyInfoserId, Date date, Date end_time,
			String credit_granting_code, String service_order_no) {

		ResultInfo result = new ResultInfo();

		// 查询当前授信用户的额度信息
		t_user_credit userCreditCheck = userCreditService.findByUserId(
				applyUserId, userId);
		if (userCreditCheck == null) {
			result.code = -1;
			result.msg = "添加或者修改额度申请表失败";
			return result;
		}

		// 增加用户授信额度明细表
		t_user_credit_detail userCreditDetail = new t_user_credit_detail();
		userCreditDetail.time = date;
		userCreditDetail.user_id = applyUserId;
		userCreditDetail.user_name = companyInfoserId;
		userCreditDetail.credit_limit_total = credit_amount_submit;
		userCreditDetail.credit_granting_code = credit_granting_code;
		userCreditDetail.start_time = userCreditCheck.start_time;
		userCreditDetail.end_time = userCreditCheck.end_time;
		userCreditDetail.lender_id = userId;
		userCreditDetail.lender_name = lenderFullName;
		userCreditDetail.usable_limit = credit_amount_submit;
		userCreditDetail.service_order_no = service_order_no;
		userCreditDetail.credit_limit_id = userCreditCheck.id;
		userCreditDetail.parent_id = 0;
		userCreditDetail.remark = "初审授信";
		boolean userCreditDetailSaveFlag = userCreditDetailService
				.save(userCreditDetail);
		if (!userCreditDetailSaveFlag) {
			result.code = -1;
			result.msg = "添加额度申请明细表失败";
			LoggerUtil.error(true, "添加额度申请明细表失败");
			return result;
		}
		result.code = 1;
		result.msg = "添加额度申请明细表成功";
		return result;
	}

	/**
	 * 修改或者增加额度申请表t_user_credit
	 * 
	 * @param credit_amount_submit
	 *            授信总额度
	 * @param financing_confine_submit
	 *            融通最高限额
	 * @param credebt_amount_submit
	 *            流转最高限额
	 * @param bond_amount_submit
	 *            保证金比例
	 * @param custodian_fee_submit
	 *            额度管理费率
	 * @param applyUserId
	 *            申请人用户id
	 * @param userId
	 *            放款人id
	 * @param lenderFullName
	 *            放款人名称
	 * @param companyInfoserId
	 *            持有人名称
	 * @param date
	 *            当前时间
	 * @param end_time
	 *            授信截止时间
	 * @param credit_granting_code
	 *            授信编号
	 * @param service_order_no
	 * @author fanghanyong
	 * @version 2018-1-19
	 * @param custodian_fee 
	 * @return
	 */
	public static ResultInfo saveCreditInfo(double credit_amount_submit,
			double financing_confine_submit, double credebt_amount_submit,
			double bond_amount_submit, double custodian_fee_submit,
			long applyUserId, long userId, String lenderFullName,
			String companyInfoserId, Date date, Date end_time,
			String credit_granting_code, String service_order_no, double custodian_fee) {

		ResultInfo result = new ResultInfo();

		// 定义用户的授信额度信息表
		t_user_credit userCreditSave = new t_user_credit();

		boolean userCreditSaveFlag = false;

		// 查询当前授信用户的额度信息
		t_user_credit userCredit = userCreditService.findByUserId(applyUserId,
				userId);
		if( bond_amount_submit > 0 && bond_amount_submit < 100){
			if (userCredit == null ) {
				// 新增授信用户额度信息
				userCreditSave.time = date;
				userCreditSave.status = 0;
				userCreditSave.user_id = applyUserId;
				userCreditSave.user_name = companyInfoserId;
				//userCreditSave.credit_limit_total = credit_amount_submit;
				userCreditSave.credit_granting_code = credit_granting_code;
				//userCreditSave.start_time = date;
				userCreditSave.end_time = end_time;
				userCreditSave.financing_confine_limit = financing_confine_submit;
				userCreditSave.bond_percent = bond_amount_submit;
				userCreditSave.lender_id = userId;
				userCreditSave.lender_name = lenderFullName;
				//userCreditSave.usable_limit = credit_amount_submit;
				userCreditSave.custodian_fee = custodian_fee_submit;
				userCreditSave.flow_limit = credebt_amount_submit;
				userCreditSave.parent_id = 0;
				//userCreditSave.pledged_limit = credit_amount_submit;
				
				//userCreditSaveFlag = userCreditService.save(userCreditSave);
				userCreditSave = userCreditService.saveT(userCreditSave);
				if (userCreditSave == null) {
					result.code = -1;
					result.msg = "添加额度申请表失败";
					LoggerUtil.error(true, "添加额度申请表失败");
					return result;
				}
				
				
			} else {
				userCredit.financing_confine_limit = financing_confine_submit;
				// 修改授信额度用户信息
				/*userCredit.credit_limit_total = userCredit.credit_limit_total
						+ credit_amount_submit;
				userCredit.usable_limit = userCredit.usable_limit
						+ credit_amount_submit;
				userCredit.pledged_limit = userCredit.pledged_limit
						+ credit_amount_submit;*/
				// 这些信息暂时不更新
				// userCredit.time = date;
				// userCredit.status = 0;
				// userCredit.user_id = applyUserId;
				// userCredit.user_name = companyInfoserId;
				// userCredit.credit_granting_code = credit_granting_code;
				// userCredit.start_time = date;
				// userCredit.end_time = end_time;
				// userCredit.bond_percent = bond_amount_submit;
				// userCredit.lender_id = userId;
				// userCredit.lender_name = lenderFullName;
				// userCredit.custodian_fee = custodian_fee_submit;
				// userCredit.flow_limit = credebt_amount_submit;
				userCreditSaveFlag = userCreditService.save(userCredit);
				if (!userCreditSaveFlag) {
					result.code = -1;
					result.msg = "修改额度申请表失败";
					LoggerUtil.error(true, "修改额度申请表失败");
					return result;
				}
				
				
			}
		}else if(bond_amount_submit == 0){
			if (userCredit == null ) {
				// 新增授信用户额度信息
				userCreditSave.time = date;
				userCreditSave.status = 0;
				userCreditSave.user_id = applyUserId;
				userCreditSave.user_name = companyInfoserId;
				userCreditSave.credit_limit_total = credit_amount_submit;
				userCreditSave.credit_granting_code = credit_granting_code;
				userCreditSave.start_time = date;
				userCreditSave.end_time = end_time;
				userCreditSave.financing_confine_limit = financing_confine_submit;
				userCreditSave.bond_percent = bond_amount_submit;
				userCreditSave.lender_id = userId;
				userCreditSave.lender_name = lenderFullName;
				userCreditSave.usable_limit = credit_amount_submit;
				userCreditSave.custodian_fee = custodian_fee_submit;
				userCreditSave.flow_limit = credebt_amount_submit;
				userCreditSave.parent_id = 0;
				userCreditSave.pledged_limit = credit_amount_submit;
				
				//userCreditSaveFlag = userCreditService.save(userCreditSave);
				userCreditSave = userCreditService.saveT(userCreditSave);
				if (userCreditSave == null) {
					result.code = -1;
					result.msg = "添加额度申请表失败";
					LoggerUtil.error(true, "添加额度申请表失败");
					return result;
				}
				
				
			} else {
				userCredit.financing_confine_limit = financing_confine_submit;
				// 修改授信额度用户信息
				userCredit.credit_limit_total = userCredit.credit_limit_total
						+ credit_amount_submit;
				userCredit.usable_limit = userCredit.usable_limit
						+ credit_amount_submit;
				userCredit.pledged_limit = userCredit.pledged_limit
						+ credit_amount_submit;
				// 这些信息暂时不更新
				// userCredit.time = date;
				// userCredit.status = 0;
				// userCredit.user_id = applyUserId;
				// userCredit.user_name = companyInfoserId;
				// userCredit.credit_granting_code = credit_granting_code;
				// userCredit.start_time = date;
				// userCredit.end_time = end_time;
				// userCredit.bond_percent = bond_amount_submit;
				// userCredit.lender_id = userId;
				// userCredit.lender_name = lenderFullName;
				// userCredit.custodian_fee = custodian_fee_submit;
				// userCredit.flow_limit = credebt_amount_submit;
				userCreditSaveFlag = userCreditService.save(userCredit);
				if (!userCreditSaveFlag) {
					result.code = -1;
					result.msg = "修改额度申请表失败";
					LoggerUtil.error(true, "修改额度申请表失败");
					return result;
				}
				
				
			}
			
		}
		
		
		result.code = 1;
		result.msg = "修改或者增加额度申请表成功";
		return result;

	}

	/**
	 * 根据放款人（用户ID）查询授信申请
	 * 
	 * @param currPage
	 * @param pageSize
	 * @param supervisor_id
	 * @return
	 * @author LiangQiongfeng
	 * @version 2018-1-20
	 */
	public PageBean<t_credit_limit> pageOfByUserId(int currPage, int pageSize,
			long supervisor_id) {
		// TODO Auto-generated method stub
		return null;
	}


	/**
	 * 分页查询 信用额度申请记录
	 * 
	 * @param currPage
	 * @param pageSize
	 * @param supervisorName
	 *            放款人姓名
	 * @param supervisorId
	 *            申请人ID
	 * @param applyName
	 *            申请人姓名
	 * @param applyUserId
	 *            融通人的ID
	 * @param stutas
	 *            授信申请状态
	 * @param startDate
	 *            申请起始时间
	 * @param endDate
	 *            申请结束时间
	 * @return
	 * @author fanghanyong
	 * @param orderValue 
	 * @param orderType 
	 * @createDate 2018年01月11日
	 */
	public PageBean<CreditLimitCompanyInfo> pageOfCreditLimit(int currPage,
			int pageSize, String supervisorName, long supervisorId,
			long applyUserId, String applyName, int status, String startDate,
			String endDate, int exports, int orderType, int orderValue) {
		return creditLimitDao.pageOfCreditLimit(currPage, pageSize,
				supervisorName, supervisorId, applyUserId, applyName, status,
				startDate, endDate, exports,orderType,orderValue);
	}

	/**
	 * 获取文件的地址
	 * 
	 * @param creditLimit
	 * @return
	 * @author fanghanyong
	 * @version 2018-1-23
	 */
	public static List getFileUtil(t_credit_limit creditLimit) {

		// 获取文件的相关信息

		// 获取财务资料
		String financialData = creditLimit.financial_data;
		List<Object> fileList = new ArrayList<Object>();
		if (StringUtils.isNotBlank(financialData)) {
			Map<String, Object> financialDataMap = new HashMap();
			String fileName = FileUtil.getFileName(financialData);
			int type = FileUtil.getFileType(financialData);
			financialDataMap.put("kind", "财务资料");
			financialDataMap.put("staticFileName", financialData);
			financialDataMap.put("fileName", fileName);
			financialDataMap.put("type", type);
			fileList.add(financialDataMap);
		}
		// 获取所得税清缴报表
		String incomeTax = creditLimit.income_tax;
		if (StringUtils.isNotBlank(incomeTax)) {
			Map<String, Object> incomeTaxMap = new HashMap();
			String fileName = FileUtil.getFileName(incomeTax);
			int type = FileUtil.getFileType(incomeTax);
			incomeTaxMap.put("kind", "所得税清缴报表");
			incomeTaxMap.put("staticFileName", incomeTax);
			incomeTaxMap.put("fileName", fileName);
			incomeTaxMap.put("type", type);
			fileList.add(incomeTaxMap);
		}
		// 获取银行对账单
		String bankStatement = creditLimit.bank_statement;
		if (StringUtils.isNotBlank(bankStatement)) {
			Map<String, Object> bankStatementMap = new HashMap();
			String fileName = FileUtil.getFileName(bankStatement);
			int type = FileUtil.getFileType(bankStatement);
			bankStatementMap.put("kind", "银行对账单");
			bankStatementMap.put("staticFileName", bankStatement);
			bankStatementMap.put("fileName", fileName);
			bankStatementMap.put("type", type);
			fileList.add(bankStatementMap);
		}
		// 获取水电费账单
		String utilityBill = creditLimit.utility_bill;
		if (StringUtils.isNotBlank(utilityBill)) {
			Map<String, Object> utilityBillMap = new HashMap();
			String fileName = FileUtil.getFileName(utilityBill);
			int type = FileUtil.getFileType(utilityBill);
			utilityBillMap.put("kind", "水电费账单");
			utilityBillMap.put("staticFileName", utilityBill);
			utilityBillMap.put("fileName", fileName);
			utilityBillMap.put("type", type);
			fileList.add(utilityBillMap);
		}
		// 获取工资表和社保表单
		String paySheet = creditLimit.pay_sheet;
		if (StringUtils.isNotBlank(paySheet)) {
			Map<String, Object> paySheetMap = new HashMap();
			String fileName = FileUtil.getFileName(paySheet);
			int type = FileUtil.getFileType(paySheet);
			paySheetMap.put("kind", "工资表和社保表单");
			paySheetMap.put("staticFileName", paySheet);
			paySheetMap.put("fileName", fileName);
			paySheetMap.put("type", type);
			fileList.add(paySheetMap);
		}
		// 获取购销合同
		String purchaseSaleContracts = creditLimit.purchase_sale_contracts;
		if (StringUtils.isNotBlank(purchaseSaleContracts)) {
			Map<String, Object> purchaseSaleContractsMap = new HashMap();
			String fileName = FileUtil.getFileName(purchaseSaleContracts);
			int type = FileUtil.getFileType(purchaseSaleContracts);
			purchaseSaleContractsMap.put("kind", "购销合同");
			purchaseSaleContractsMap.put("staticFileName",
					purchaseSaleContracts);
			purchaseSaleContractsMap.put("fileName", fileName);
			purchaseSaleContractsMap.put("type", type);
			fileList.add(purchaseSaleContractsMap);
		}
		// 获取融通增信资料
		String finCreditInfo = creditLimit.financing_credit_information;
		if (StringUtils.isNotBlank(finCreditInfo)) {
			Map<String, Object> finCreditInfoMap = new HashMap();
			String fileName = FileUtil.getFileName(finCreditInfo);
			int type = FileUtil.getFileType(finCreditInfo);
			finCreditInfoMap.put("kind", "融通增信资料");
			finCreditInfoMap.put("staticFileName", finCreditInfo);
			finCreditInfoMap.put("fileName", fileName);
			finCreditInfoMap.put("type", type);
			fileList.add(finCreditInfoMap);
		}
		// 获取其他资料
		String otherInfo = creditLimit.other_information;
		if (StringUtils.isNotBlank(otherInfo)) {
			Map<String, Object> otherInfoMap = new HashMap();
			String fileName = FileUtil.getFileName(otherInfo);
			int type = FileUtil.getFileType(otherInfo);
			otherInfoMap.put("kind", "其他资料");
			otherInfoMap.put("staticFileName", otherInfo);
			otherInfoMap.put("fileName", fileName);
			otherInfoMap.put("type", type);
			fileList.add(otherInfoMap);
		}
		return fileList;
	}

	/**
	 * 查询 信用额度申请记录，统计授信申请总额度
	 * 
	 * @param supervisorName
	 *            放款人姓名
	 * @param supervisorId
	 *            放款人ID
	 * @param applyName
	 *            申请人姓名
	 * @param applyUserId
	 *            融通人的ID
	 * @param stutas
	 *            授信申请状态
	 * @param startDate
	 *            申请起始时间
	 * @param endDate
	 *            申请结束时间
	 * @return
	 * @author fanghanyong
	 * @createDate 2018年01月24日
	 */
	public double totalCreditLimit(String supervisorName, long supervisorId,
			long applyUserId, String applyName, int status, String startDate,
			String endDate) {

		return creditLimitDao.totalCreditLimit(supervisorName, supervisorId,
				applyUserId, applyName, status, startDate, endDate);
	}

	/**
	 *	后台---风控---授信额度申请展示
	 * @param currPage
	 * @param pageSize
	 * @param lender_name
	 * @param drawee
	 * @param showType
	 * @param orderValue
	 * @return
	 * @author Liangqiongfeng
	 *@version 2018-3-2 
	 */
	public PageBean<CreditLimitCompanyInfo> pageOfCreditLimit(int currPage,
			int pageSize, String lender_name, String drawee, int showType,
			int orderValue) {
		
		return creditLimitDao.pageOfCreditLimit(currPage,
				pageSize,lender_name,drawee,showType,orderValue);
	}
	
	/**
	 * 获取文件的地址
	 * 
	 * @param creditLimit
	 * @return
	 * @author Liangqiongfeng
	 * @version 2018-1-23
	 */
	public static String[] getFileURL(t_credit_limit creditLimit) {

		// 获取文件的相关信息

		// 获取财务资料
		String financialData = creditLimit.financial_data;
		String[] path = new String[8];
		if (StringUtils.isNotBlank(financialData)) {
			 
			path[0] = financialData;
		}
		// 获取所得税清缴报表
		String incomeTax = creditLimit.income_tax;
		if (StringUtils.isNotBlank(incomeTax)) {
			path[1] = incomeTax;
		}
		// 获取银行对账单
		String bankStatement = creditLimit.bank_statement;
		if (StringUtils.isNotBlank(bankStatement)) {
			path[2] = bankStatement;
		}
		// 获取水电费账单
		String utilityBill = creditLimit.utility_bill;
		if (StringUtils.isNotBlank(utilityBill)) {
			path[3] = utilityBill;
		}
		// 获取工资表和社保表单
		String paySheet = creditLimit.pay_sheet;
		if (StringUtils.isNotBlank(paySheet)) {
			path[4] = paySheet;
		}
			
		// 获取购销合同
		String purchaseSaleContracts = creditLimit.purchase_sale_contracts;
		if (StringUtils.isNotBlank(purchaseSaleContracts)) {
			path[5] = purchaseSaleContracts;
		}
		// 获取融通增信资料
		String finCreditInfo = creditLimit.financing_credit_information;
		if (StringUtils.isNotBlank(finCreditInfo)) {
			path[6] = finCreditInfo;
		}
		// 获取其他资料
		String otherInfo = creditLimit.other_information;
		if (StringUtils.isNotBlank(otherInfo)) {
			path[7] = otherInfo;
		}
		return path;
	}

	/**
	 * 修改授信申请资料
	 * @param creditLimitId 授信id
	 * @param userId 申请id
	 * @param request_limit 申请额度
	 * @param remark 申请说明
	 * @param financial_data 资料
	 * @param income_tax
	 * @param bank_statement
	 * @param utility_bill
	 * @param pay_sheet
	 * @param purchase_sale_contracts
	 * @param financing_credit_information
	 * @param other_information
	 * @return
	 * @author Liangqiongfeng
	 *@version 2018-4-8 
	 */
	public ResultInfo updateUserCreditDetail(long creditLimitId, long userId,
			double request_limit, String remark, 
			String financial_data, String income_tax, String bank_statement,
			String utility_bill, String pay_sheet,
			String purchase_sale_contracts,
			String financing_credit_information, String other_information) {
		// TODO Auto-generated method stub
		return creditLimitDao.updateUserCreditDetail(creditLimitId,
				userId,request_limit, remark, financial_data,
				income_tax, bank_statement, utility_bill, pay_sheet,
				purchase_sale_contracts, financing_credit_information,
				other_information);
	}

	/**
	 * 放款人授予授信额度
	 * @param credit_limit_id 授信申请表id 
	 * @param bill_code 授信编号
	 * @param company_id 授信申请人user_id 
	 * @param receive_company_id 放款人user_id 
	 * @param is_loan 是否放款 0 未放款，1 已放款
	 * @return
	 * @author liangqiongfeng
	 *@version 2018-4-14 
	 * @param bond_agreement 
	 */
	public ResultInfo makeLoan(long credit_limit_id, String bill_code,
			long company_id, long receive_company_id, int is_loan, int bond_agreement) {
		
		ResultInfo result = new ResultInfo(); 
		
		if(is_loan == 0 && bond_agreement == 1){
			
			t_credit_limit credit_limit = creditLimitDao.findByID(credit_limit_id);
			if(credit_limit == null){
				result.code = -1;
				result.msg = "获取不到授信申请信息";
				return result;
			}
			// 查询当前授信用户的额度信息
			t_user_credit userCredit = userCreditService.findByUserId(company_id,
					receive_company_id);
			if(userCredit == null){
				result.code = -1;
				result.msg = "获取不到授信信息";
				return result;
			}
			
			// 业务流水号
			String service_order_no = OrderNoUtil.getNormalOrderNo(
					ServiceType.DONEORDER_QUERY, "");

			
			int endMonth = DateUtil.creditLenderMonth(credit_limit.start_time, credit_limit.end_time);
			
			// 流转费用的结算
			ResultInfo resultfee = digitalCommercialPaperService
					.userTransaction(company_id, receive_company_id,
							credit_limit.audit_amount, endMonth,
							userCredit.custodian_fee,service_order_no);
			//额度管理费
			double custodian_fee = Arith.div(Arith.mul(
					Arith.mul(credit_limit.audit_amount, userCredit.custodian_fee),
					endMonth), 100, 2);
			if(resultfee.code==0){
				
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("lenderFullName", userCredit.lender_name);
				param.put("applyUserName", userCredit.user_name);
				param.put("request_limit_submit", credit_limit.request_limit);
				param.put("credit_amount_submit", credit_limit.audit_amount);
				param.put("custodian_fee_submit", custodian_fee);
				noticeService.sendSysNotice(credit_limit.user_id,
						NoticeScene.PACKAGING_USER_LIMIT_SUCC, param);
				result.code = -1;
				result.msg = resultfee.msg;
				return result;
			}else if (resultfee.code == -1) {
				result.code = -1;
				result.msg = resultfee.msg;
				return result;
			}
			
			userCredit.credit_limit_total  += credit_limit.audit_amount;
			userCredit.usable_limit += credit_limit.audit_amount;
			userCredit.pledged_limit += credit_limit.audit_amount;
			if(userCredit.start_time == null){
				userCredit.start_time = new Date();
			}
			boolean save = userCreditService.updateBySQL(userCredit);
			if(!save){
				result.code = -1;
				result.msg = "更新授信额度信息失败";
				return result;
			}
			
			// 添加额度申请明细表t_user_credit_detail
			ResultInfo resultCreditDetailInfo = CreditDetail(
					credit_limit.audit_amount, company_id, receive_company_id, userCredit.lender_name,
					userCredit.user_name, new Date(), userCredit.end_time,userCredit.credit_granting_code,
					service_order_no);

			if (resultCreditDetailInfo.code < 1) {
				LoggerUtil.error(true, resultCreditDetailInfo.msg);
				result.code = -1;
				result.msg = resultCreditDetailInfo.msg;
				return result;
			}
			
			//获取该授信申请绑定的应付账款信息
			t_receivables_push receivables_push = receivablesPushService.findTRPBySql(credit_limit_id,receive_company_id,company_id);
			
			t_creditor_right_debt creditorRightDebt = creditorRightDebtService.findByID(receivables_push.creditor_right_id);
			
			//根据绑定的应付账款信息，将一部分授信额度直接转给应付账款债权人
			result = userCreditService.toApply(creditorRightDebt,company_id,
					receive_company_id);
			if (result.code < 1) {
				return result;
			}
			
			
			
			//审核成功，通知授信申请用户
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("lenderFullName", userCredit.lender_name);
			param.put("applyUserName", userCredit.user_name);
			param.put("request_limit", credit_limit.request_limit);
			param.put("credit_amount_submit", credit_limit.audit_amount);
			param.put("custodian_fee_submit", custodian_fee);
			
			param.put("start_time", credit_limit.start_time);
			param.put("end_time",  credit_limit.end_time);
			param.put("ratio", userCredit.financing_confine_limit);
			
			noticeService.sendSysNotice(credit_limit.user_id,
					NoticeScene.PACKAGING_CREDIT_LIMIT_SUCC, param);
			
		}
		return result;
	}
	
	/**
	 * 生成授信申请表记录
	 * @param userId 申请用户id
	 * @param financial_data
	 * @param income_tax
	 * @param bank_statement
	 * @param utility_bill
	 * @param pay_sheet
	 * @param purchase_sale_contracts
	 * @param financing_credit_information
	 * @param other_information
	 * @return
	 */
	public ResultInfo updateUserCreditDetail(long userId,
			String financial_data, String income_tax, String bank_statement,
			String utility_bill, String pay_sheet,
			String purchase_sale_contracts,
			String financing_credit_information, String other_information) {
		
		ResultInfo result = new ResultInfo();
		
		
		t_credit_limit creditLimit = new t_credit_limit();
		
		creditLimit.user_id = userId;
		creditLimit.financial_data = financial_data;
		creditLimit.income_tax = income_tax;
		creditLimit.bank_statement = bank_statement;
		creditLimit.utility_bill = utility_bill;
		creditLimit.pay_sheet = pay_sheet;
		creditLimit.purchase_sale_contracts = purchase_sale_contracts;
		creditLimit.financing_credit_information = financing_credit_information;
		creditLimit.other_information =other_information ;
		
		t_credit_limit credit_limit = creditLimitDao.saveT(creditLimit);
		if(credit_limit == null){
			result.code = -1;
			result.msg = "授信申请资料保存失败";
			return result;
		}
		
		result.code = 1;
		result.msg = "授信申请资料保存成功";
		result.obj = credit_limit;
		return result;
	}

	/**
	 * 数据资料的校验
	 * @param financial_data
	 * @param income_tax
	 * @param bank_statement
	 * @param utility_bill
	 * @param pay_sheet
	 * @param purchase_sale_contracts
	 * @param financing_credit_information
	 * @param other_information
	 * @return
	 */
	public ResultInfo Validate(String financial_data, String income_tax,
			String bank_statement, String utility_bill, String pay_sheet,
			String purchase_sale_contracts,
			String financing_credit_information, String other_information) {
		
		int count = 0;
		
		ResultInfo result = new ResultInfo();
		
		if(StringUtils.isBlank(financial_data)){
			count += 1;
		}
		if(StringUtils.isBlank(income_tax)){
			count += 1;
		}
		if(StringUtils.isBlank(bank_statement)){
			count += 1;
		}
		if(StringUtils.isBlank(utility_bill)){
			count += 1;
		}
		if(StringUtils.isBlank(pay_sheet)){
			count += 1;
		}
		if(StringUtils.isBlank(purchase_sale_contracts)){
			count += 1;
		}
		if(StringUtils.isBlank(financing_credit_information)){
			count += 1;
		}
		if(StringUtils.isBlank(other_information)){
			count += 1;
		}
		if(count == 0){
			result.code = -1;
			result.msg = "授信申请人没上传授信资料";
			return result;
		}
		result.code = 1;
		result.msg = "授信申请人没上传授信资料";
		return result;
	}
	
	/**
	 * 保存授信申请信息并返回对象
	 * 微信端申请授信第一步
	 * @param creditLimit
	 * @return
	 */
	public t_credit_limit saveT(t_credit_limit creditLimit) {
		
		return creditLimitDao.saveT(creditLimit);
	}
	
	/**
	 * 查询授信总额
	 * @param userId 放款人用户id
	 * @param applyName
	 * @param showType
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public double findTotal(long userId, String applyName, int showType,
			String startDate, String endDate) {
		return creditLimitDao.findTotal(userId,applyName,showType,startDate,endDate);
	}
	
	/**
	 * 微信端申请授信第二步
	 * @param userId 用户id
	 * @param creditLimitId 授信申请表id
	 * @param credit_amount 申请授信额度
	 * @param credit_remark  申请授信说明
	 * @return
	 */
	public boolean upadateById(long userId, long creditLimitId,
			double credit_amount, String credit_remark) {
		
		StringBuffer updateSql = new StringBuffer("UPDATE `t_credit_limit` SET  `request_limit`=:request_limit, `remark`=:remark WHERE id = :id AND user_id = :user_id");
		
		Map<String,Object> condition = new HashMap<String,Object>();
		
		condition.put("request_limit", credit_amount);
		condition.put("remark", credit_remark);
		condition.put("id", creditLimitId);
		condition.put("user_id", userId);
		
		return creditLimitDao.updateBySQL(updateSql.toString(), condition) > 0 ? true:false;
	}

	
}
